<template>
    <div>
      <!-- 查询 -->
      <div>
        <el-input v-model="name" placeholder="请输入姓名" size="small" suffix-icon="el-icon-search"
                  style="width: 160px;margin-bottom: 10px;"></el-input>
        <el-select v-model="sex" size="small"  style="width: 160px;margin-left: 5px;" placeholder="请选择性别">
          <el-option
              v-for="item in sexs"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-button type="primary" size="small" @click="findPage" style="margin-left: 5px" >查询</el-button>
        <el-button type="success" size="small" @click="resetParam"  style="margin-left: 5px" >重置</el-button>
        <el-button type="warning" size="small" @click="add" style="margin-left: 5px" >新增</el-button>
      </div>
      <!--  用户列表  -->
      <el-table :data="tableData" :header-cell-style="{background:'#e9edf6'}" border  :cell-style="{textAlign:'center'}">
        <el-table-column prop="id" label="ID" width="60">
        </el-table-column>
        <el-table-column prop="no" label="账号" width="180">
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80">
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80">
          <template slot-scope="scope">
            <el-tag
                :type="scope.row.sex === 1 ? 'primary' : 'success'"
                disable-transitions>{{scope.row.sex === 1 ? '男' : '女'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roleId" label="角色" width="160">
          <template slot-scope="scope">
            <el-tag
                :type="scope.row.roleId === 0 ? 'danger' : (scope.row.roleId === 1 ? 'primary' : 'success')"
                disable-transitions>{{scope.row.roleId === 0 ? '超级管理员' :
                (scope.row.roleId === 1 ? '管理员' : '用户')}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="operate" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加分页组件 -->
      <div class="block">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
      <!-- 新增/编辑的弹出框 -->
      <el-dialog
          title="用户信息"
          :visible.sync="centerDialogVisible"
          width="30%"
          center>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="账号" prop="no">
            <el-col :span="16">
              <el-input size="small" v-model="form.no"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-col :span="16">
              <el-input size="small" v-model="form.password"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-col :span="16">
              <el-input size="small" v-model="form.name"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-col :span="16">
              <el-input size="small" v-model="form.age"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-col :span="16">
              <el-input size="small" v-model="form.phone"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="性别" >
            <el-col :span="16">
              <el-radio-group v-model="form.sex">
                <el-radio label="1">男</el-radio>
                <el-radio label="0">女</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </span>
      </el-dialog>

    </div>
</template>


<style scoped>

</style>

<script>
export default {
  name: 'Main',
  data() {
    let checkAge = (rule, value, callback) => {//对年龄进行校验
      if(value>150){
        callback(new Error('年龄输入过大'));
      }else{
        callback();
      }
    };

    let checkDuplicate =(rule,value,callback)=>{
      if(this.form.id){
        return callback();
      }
      this.$axios.get("http://localhost:8090/user/findByNo/"+this.form.no).then(res=>{
        if(res.data.code!=200){
          callback()
        }else{
          callback(new Error('账号已经存在'));
        }
      })
    };
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      name:'',
      sex:'',
      sexs:[
        {
          value:1,
          label:'男'
        },
        {
          value:0,
          label:'女'
        }
      ],
      centerDialogVisible: false,
      form: {
        id: null,
        no: '',
        password: '',
        name: '',
        age: '',
        sex: '0',
        phone: '',
        roleId: 1
      },
      rules: {//校验规则
        no: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
          //校验账号是否重复
          { validator: checkDuplicate, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          //长度1到3
          { min: 1, max: 3, message: '长度在 1 到 3 位', trigger: 'blur' },
          //校验年龄的正则
          { pattern: /^[0-9]\d{0,2}$/, message: '请输入正确的年龄', trigger: 'blur' },
          //使用函数checkAge校验年龄是否合理
          { validator: checkAge, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          //校验手机的正则
          { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  methods:{
    loadGet() {
      this.$axios.get("http://localhost:8090/user/list").then(res => {
        console.log(res.data);
        console.log(res.data.data)
        this.tableData = res.data.data
      })
    },
    findPage(){
      this.$axios.post("http://localhost:8090/user/listPage",{
        currentPage:this.currentPage,
        pageSize:this.pageSize,
        param:{//封装的
          name:this.name,
          sex:this.sex
        }
      }).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total

      })
    },
    handleSizeChange(val) {//页面尺寸发生变化的时候触发
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.findPage();

    },
    handleCurrentChange(val) {//改变当前页码的时候触发
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.findPage();
    },
    resetParam(){//重置查询条件
      this.name = ''
      this.sex = ''

      // this.findPage()
    },
    //添加resetForm函数，重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    add(){
      this.centerDialogVisible = true;
      //重置表单数据
     /* this.$nextTick(() => {
        this.resetForm('form');
      });*/
      this.form = {
        id: null,
        no: '',
        password: '',
        name: '',
        age: '',
        sex: '0',
        phone: '',
        roleId: 1
      };
    },
    doSave(){//新增功能
      this.$axios.post("http://localhost:8090/user/save",this.form).then(res=>{
        if(res.data.code == 200){
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
          // 关闭窗口
          this.centerDialogVisible = false;
          // 新增数据实时显示
          this.findPage();
        }else{
          this.$message({
            type: 'error',
            message: '保存失败!'
          });
        }
      })
    },
    doEdit(){//编辑功能
      this.$axios.put('http://localhost:8090/user/edit',this.form).then(res=>{
        if(res.data.code == 200){
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          // 关闭窗口
          this.centerDialogVisible = false;
          // 新增数据实时显示
          this.findPage();
        }else{
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        }
      })
    },
    save(){
      this.$refs.form.validate((valid) => {//表单数据校验
        if (valid) {//校验通过
          //判断是新增还是编辑
          if(this.form.id){
            this.doEdit();//编辑
          }else{
            this.doSave();//新增
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleEdit(i,row){//i：下标,row：当前的用户
      // console.log(i)
      console.log(row)
      //1.弹出编辑框
      this.centerDialogVisible = true;
      this.form = row;
      //将性别由number类型，转换为字符串，页面才会有效果！
      this.form.sex = this.form.sex+''
      this.form.age = this.form.age+''
      /*this.$axios.get("http://localhost:8090/user/findById/"+row.id).then(res=>{
        this.form = res.data.data
        //将性别由number类型，转换为字符串，页面才会有效果！
        this.form.sex = this.form.sex+''
        this.form.age = this.form.age+''
      })*/

    },
  },
  mounted() {
    // this.loadGet()
    this.findPage()
  }
}
</script>